<!--
 * @Description: 星巴克多选
 * @Author: Kerwin
 * @Date: 2025-05-08 16:19:21
 * @LastEditTime: 2025-11-06 15:01:58
 * @LastEditors:  Please set LastEditors
-->
<template>
    <view class="goodsChoose">

        <!-- 可选类 -->
        <view class="optionalBox" v-if="goodsItem.optional">
            <view class="optionalItem" v-for="(item, index) in goodsItem.optional" :key="item.id">
                <view class="goodsName">{{ item.name }}</view>
                <view class="goodsItem">
                    <view class="optional" :class="{ activeOptional: goods.checked }"
                        @click="handleOptionalClick(item.id, goods.id)" v-for="(goods, index) in item.sku_infos"
                        :key="goods.id">
                        <u-image v-if="goods.img" style="margin: auto;" :showLoading="true" :src="goods.img"
                            width="80rpx" height="80rpx"></u-image>
                        <!-- <u-image style="margin: auto;" :showLoading="true" :src="itemImg" width="80rpx"
                            height="80rpx"></u-image> -->
                        <view class="name">
                            {{ goods.name }} <text v-if="goods.price != 0 && goods.price">|</text> <text
                                class="goods-price" v-if="goods.price != 0 && goods.price">￥{{ goods.price }}</text>
                        </view>

                        <!-- 售罄蒙版 -->
                        <view class="mode" v-if="goods.enable === false">
                            <view class="mode-text">售罄</view>
                        </view>
                    </view>


                </view>

            </view>

        </view>
        <!-- 提示信息 -->
        <view class="mes">
            1．划线价格：商品展示的划横线的价格是参考价格，并非商品原价而是指不参加优惠的情况下，单品门店价格的总和（单品价总和）。当套餐内容可由您选择组合时，以套餐内可选商品的最低单价总和为为划线价，该价格仅供您参考。
            说明：
            2．非划线价格指参与优惠、使用抵扣券或代金券、在活动时间或满足活动条件、按照套餐组合购买的前提下可能支付的价格，具体的成交价格可能因参加其他活动等而发生变化，最终成交价格以订单结算页价格为准。
            3．产品及包装请以实物为准，图片仅供参考
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, toRaw, toRefs, watch, nextTick } from 'vue'
import itemImg from '@/static/xfl/item.png'
//props
const props = defineProps({
    product: {
        type: Object,
        default: () => ({})
    },
    productChoose: {  //商品是否可选规则
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['chooseOptional'])
const goodsItem = ref()


// 选中状态变化时触发 item：最外层温度的id goods是小料的id
const handleOptionalClick = (item: string, goods: any) => {
    if (goods.enable === false) return
    goodsItem.value.optional.forEach((group: any) => {
        if (group.id === item) {
            group.sku_infos.forEach((ingredient: any) => {
                ingredient.checked = ingredient.id === goods
            })
        }
    })

    // // 触发计算并通知父组件
    const selectedIngredients = getSelectedIngredients()
    goodsItem.value.otherStr = selectedIngredients
    goodsItem.value.otherCheckStr = '/' + selectedIngredients.map(item => {
        let str = ''
        if (Number(item.price) != 0) {
            str = item.name + `￥${item.price}`
        } else {
            str = item.name
        }
        return str
    }).join('/')
    emit('chooseOptional', goodsItem.value)
}

// 获取所有被选中的小料的传递格式
const getSelectedIngredients = (): { price: string; specificationId: string; name: string; skuId: string }[] => {
    const selectedIngredients: { price: string; specificationId: string; name: string; skuId: string }[] = []
    if (!goodsItem.value?.optional) return selectedIngredients
    goodsItem.value.optional.forEach((group: any) => {
        if (Array.isArray(group.sku_infos)) {
            group.sku_infos.forEach((ingredient: any) => {
                if (ingredient.checked) {
                    selectedIngredients.push({
                        specificationId: group.id,
                        name: ingredient.name,
                        skuId: ingredient.id,
                        price: ingredient.price
                    })
                }
            })
        }
    })
    return selectedIngredients
}

// 根据选中小料匹配对应的 sku
const findMatchingSku = (selectedIngredients: string[]) => {
    const { sku_infos: skus } = goodsItem.value

    if (!Array.isArray(skus)) return null

    return skus.find((sku: any) => {
        if (!Array.isArray(sku.values)) return false

        const specNames = sku.values.map((v: any) => v.spec_name)

        return (
            selectedIngredients.length === specNames.length &&
            selectedIngredients.every(name => specNames.includes(name))
        )
    })
}

// 初始化默认选中项
const initDefaultSelection = () => {
    const selectedIngredients = getSelectedIngredients()
    // console.log('初始化默认选中项', selectedIngredients);
    goodsItem.value.otherStr = selectedIngredients
    goodsItem.value.otherCheckStr = '/' + selectedIngredients.map(item => {
        let str = ''
        if (Number(item.price) != 0) {
            str = item.name + `￥${item.price}`
        } else {
            str = item.name
        }
        return str
    }).join('/')
    emit('chooseOptional', goodsItem.value)
}

// 监听 product 变化，重新初始化
watch(
    () => props.product,
    (newVal) => {
        if (newVal) {
            goodsItem.value = JSON.parse(JSON.stringify(newVal))
            initDefaultSelection()
        }
    },
    { immediate: true, deep: true }
)


</script>

<style lang="scss" scoped>
.goodsChoose {
    // height: calc(100vh - 400rpx);
    // margin-bottom: 1300rpx;
    background-color: #fff;

}

.goodsSize1 {

    .goodsItem {
        display: flex;
        flex-wrap: wrap;


        .required {
            width: 150rpx;
            height: 160rpx;
            border-radius: 10rpx;
            text-align: center;
            margin: 30rpx;
            // margin-bottom: 50rpx;
            border: 2rpx solid #f1f1f1;

            // .img{
            //     height: 160rpx;

            // }
            .name {
                font-size: 24rpx;
            }
        }
    }


    .goodsSize1_1 {
        font-weight: 700;
        margin: 40rpx 0;
    }

    .goodsSize1_2 {
        margin-bottom: 40rpx;
    }

}

.optionalBox {
    .optionalItem {
        .goodsItem {
            display: flex;
            flex-wrap: wrap;

            .optional {
                position: relative;
                width: 150rpx;
                // height: 60rpx;
                padding: 10rpx 0;

                // line-height: 60rpx;
                border: 2rpx solid #f1f1f1;
                border-radius: 10rpx;
                text-align: center;
                margin: 30rpx;
                // margin-bottom: 80rpx;
                background-color: #f6f5f8;
                //color: #949496;

                .mode {
                    position: absolute;
                    top: 0;
                    width: 100%;
                    height: 100%;
                    background-color: rgba(25, 14, 14, 0.4);

                    .mode-text {
                        color: #e9e9e9;
                    }
                }

                .name {
                    font-size: 24rpx;
                }
            }
        }

    }
}


.goodsName {
    font-size: 28rpx;
    // color: #969696;
    color: #333;
    font-weight: 700;
    margin: 20rpx 0;


}

.mes {
    height: 500rpx;
    font-size: 20rpx;
    color: #969696;
    margin-top: 50rpx;
}

//选中了小料
.activeOptional {
    color: #ea7721 !important;
    border: 2rpx solid #ff6c18 !important;
    background-color: #fef1ec !important;
    /* 蓝色半透明蒙版 */
    //   opacity: 0.8; /* 可选：整体透明度控制 */
}

.goods-price {
    font-size: 26rpx;
    color: #f05a5a;
    font-weight: 700;
}
</style>
